//
//  M_OrderVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/30.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class M_OrderVC: BaseFormViewController,UITableViewDataSource,UITableViewDelegate {
    
    static let cellIDStr : String = "M_OrderCell"
    static let addressIDStr : String = "M_OrderCellAddress"
    
    
    var tableView = UITableView(frame: CGRect.zero, style: .grouped)
    let footView = M_OrderFootView()
    let sumLab = UILabel()
    
    let btmtoolView = UIView()
    
//    let addressBox = UIView()
//    let addressLab = UILabel()
    let addressView = M_OrderAddressView()
    
    //商品详情数据
    var proAry : [[String: Any?]]
    //配送地址/方式
    var curAdDic = [String: Any?]()
    //订单表单提交时用
    var orderData : OrderDataClass
    var lastView : UIView?
    var iscar = false
    
    init(_ order : OrderDataClass, info: [[String: Any?]]) {
        self.proAry = info
        self.orderData = order
        super.init()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        getUserList(isDefault: true,callback: { sec in
            self.setupFootView()
        })
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func getSendPrice(callback: @escaping ([String:Any?]) -> Void) {
        let orderDeliverModeCode = self.curAdDic.getString("orderDeliverModeCode") ?? ""
        let orderDeliverSiteCode = self.curAdDic.getString("orderDeliverSiteCode") ?? ""
        if orderDeliverSiteCode.count == 0 || orderDeliverSiteCode.count == 0 {
            return
        }
        MBProgressHUD.showOrIncrease(showText: "正在提交")
        var items = [[String:Any?]]()
        for var dic in proAry {
            if dic["productNum"] == nil {
                dic.updateValue(1, forKey: "productNum")
            }
            items.append(dic)
        }
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "orderDeliverModeCode":orderDeliverModeCode,
                                    "orderDeliverSiteCode":orderDeliverSiteCode,
                                    "items":items]
        API.request(url: .M_FreightCaculator, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let dl = result.data?.getDictionary("data")
                {
                    callback(dl)
                }
            }
            else {
                let popup = PopupSureBox(title: "无法获取运费", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
        
    }
    
    func getUserList(isDefault: Bool=false, callback: @escaping (Bool) -> Void) {
        MBProgressHUD.showOrIncrease(showText: "正在提交")
        var params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        if isDefault {
            params.updateValue(isDefault, forKey: "isDefault")
        }
        API.request(url: .M_GetUserContactAddressList, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let dl = result.data?.getDictionary("data")?.getDictList("contactAddress"),dl.count > 0 {
                    let dic = dl[0]
                    var ad = dic.getString("provinceName") ?? ""
                    ad += dic.getString("cityName") ?? ""
                    ad += dic.getString("districtName") ?? ""
                    ad += dic.getString("townName") ?? ""
                    ad += dic.getString("detailAddress") ?? ""
//                    self.addressLab.text = ad
                    self.addressView.nameAndMobileLabel.text =  "\(dic.getString("receiptName") ?? "") \(dic.getString("mobile") ?? "")"
                    self.addressView.addressLabel.text = ad
                    self.curAdDic.updateValue("103002", forKey: "orderDeliverModeCode")
                    self.curAdDic.updateValue(anyToString(dl[0].getInt("contactID")), forKey: "orderDeliverSiteCode")
                    self.curAdDic.updateValue(dl[0].getString("detailAddress"), forKey: "name")
                    self.addressView.noneLabel.text = ""
                    self.tableView.reloadData()
                    callback(true)
                }
                else {
                    self.addressView.noneLabel.text = "选择配送地址"
                    self.tableView.reloadData()
                    callback(false)
                }
            }

            callback(false)
        }
    }

    func submitOrderData(orderDeliverModeCode: String, orderDeliverSiteCode: String, zoneCode: String, remark: String, items: [[String:Any?]], callback: @escaping ([String:Any?]) -> Void) {
        MBProgressHUD.showOrIncrease(showText: "正在提交")
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "orderDeliverModeCode":orderDeliverModeCode,
                                    "orderDeliverSiteCode":orderDeliverSiteCode,
                                    "zoneCode":zoneCode,
                                    "remark":remark,
                                    "items":items]
        API.request(url: .M_SubmitOrder, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let dl = result.data?.getDictionary("data")
                {
                    callback(dl)
                }
            }
            else {
                let popup = PopupSureBox(title: result.errMsg ?? "下单失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
    
    func submitOrderCar(orderdata: OrderDataClass, callback: @escaping ([String:Any?]) -> Void) {
        MBProgressHUD.showOrIncrease(showText: "正在提交")
        var params :[String:Any] = orderdata.toDictionary()
        params.updateValue(LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "", forKey: "identityToken")
        API.request(url: .M_CartSubmitOrder, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()

            let noT = NSNotification.Name(rawValue: CAR_CHANGE)
            let dic = ["key":"value"]
            NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
            
            if result.success {
                if let dl = result.data?.getDictionary("data")
                {
                    callback(dl)
                }
            }
            else {
                let popup = PopupSureBox(title: result.errMsg ?? "下单失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
}

class M_OrderCellHideProductNo : M_OrderCell {
    override var showProductNo: Bool { return false}
}

// MARK: UI
extension M_OrderVC {
    func setupFootView() {
        var pricesum = 0.0
        for item in proAry {
            pricesum += anyToDouble(item["employeeCentPrice"] as Any?) ?? (anyToDouble(item["productPrice"] as Any?) ?? 0.0)*(anyToDouble(item["productNum"] as Any?) ?? 0.0)
        }
        footView.priceLab.text = anyToString(pricesum)?.quXiaoShuDianHouDeLing
        getSendPrice(callback: { (data) in
            let sendprice = anyToDouble(data["totalFreight"] ?? 0) ?? 0
            self.footView.sendPriceLab.text = anyToString(sendprice)?.quXiaoShuDianHouDeLing
            
            var productTotal = 0
            for dic in self.proAry {
                productTotal += anyToInt(dic["productNum"] as Any?) ?? 1
            }
            self.footView.pudNum.text = "共" + (anyToString(productTotal) ?? "0") + "件商品  小计 " + (anyToString(pricesum+sendprice)?.quXiaoShuDianHouDeLing ?? "0")
            self.sumLab.text = anyToString(pricesum+sendprice)?.quXiaoShuDianHouDeLing ?? "0"
        })
    }
    
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        headTitle.text = "填写订单"
        
        //画横线
//        let line = headView.drawView { (make) in
//            make.left.right.equalToSuperview()
//            make.bottom.equalToSuperview().offset(-1)
//            make.height.equalTo(2)
//        }
//        line.backgroundColor = .xF2F2F2
        
//        drawAddressBox()
        
        let btm = 50
        ///底部工具条部分
        safeView.drawView(view: btmtoolView) { (make) in
            make.bottom.equalToSuperview().offset(btm)
            make.left.right.equalToSuperview()
            make.height.equalTo(100)
        }
        btmtoolView.backgroundColor = .white

                
//                画横线
        let line = btmtoolView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        let buyBtn = btmtoolView.drawButton(title: "提交订单", titleColor: .white, fontSize: 14) { (make) in
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(10)
            make.height.equalTo(35)
            make.width.equalTo(110)
        }
        buyBtn.backgroundColor = .xFC4C02
        buyBtn.layer.cornerRadius = 17.5
        buyBtn.addTarget(self, action: #selector(_buyButtonClick(button:)), for: .touchUpInside)
        
        btmtoolView.drawLabel(text: "(含运费)", fontSize: 12, textColor: .x999999) { (make) in
            make.right.equalTo(buyBtn.snp.left).offset(-10)
            make.top.equalToSuperview().offset(30)
        }

        var dl : [String:Any?]?
        if proAry.count > 0 {
            dl = proAry[0]
        }
        let dl1 = LocalStorage.getDic(forKey: DEFULT_MALL)
        let centUnitName = dl?.getString("centUnitName") ?? dl1?.getString("centName") ?? ""
        let lab = btmtoolView.drawLabel(text: centUnitName, fontSize: 12, textColor: .x999999) { (make) in
            make.right.equalTo(buyBtn.snp.left).offset(-10)
            make.top.equalToSuperview().offset(15)
        }
        
        btmtoolView.drawLabel(label: sumLab,text: "", fontSize: 18, textColor: .xFC4C02) { (make) in
            make.right.equalTo(lab.snp.left).offset(-10)
            make.top.equalToSuperview().offset(12)
        }
        
        btmtoolView.drawLabel(text: "合计", fontSize: 12, textColor: .x333333) { (make) in
            make.right.equalTo(sumLab.snp.left).offset(-10)
            make.top.equalToSuperview().offset(15)
        }
        

        //添加列表
        safeView.addSubview(tableView)
        tableView.backgroundColor = UIColor.clear;
        tableView.register(M_OrderCellHideProductNo.self, forCellReuseIdentifier: M_OrderVC.cellIDStr)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: M_OrderVC.addressIDStr)
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.allowsMultipleSelection = true
        tableView.snp.makeConstraints { (make) in
//            make.top.equalTo(addressBox.snp.bottom).offset(10)
            make.top.equalTo(headView.snp.bottom).offset(1)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(btmtoolView.snp.top)
        }
        
        drawRightButton(imageName: "xiangqingkefu_82")
        .addTarget(self, action: #selector(_kefuButtonClick(button:)), for: .touchUpInside)
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

    }
    
    func drawAddressBox(parentView:UIView)->UIView{
//        let addressBox = parentView.drawView() { (make) in
//            make.top.equalTo(headView.snp.bottom).offset(10)
//            make.left.right.equalToSuperview()
////            make.height.equalTo(52.5)
//        }
        let addressBox = parentView.drawView() { (make) in
            make.top.bottom.equalToSuperview()
            make.left.right.equalToSuperview()
//            make.height.equalTo(52.5)
        }
        addressBox.backgroundColor = .white
        
//        addressBox.drawImage(named: "xuanzhedizhi_93") { (make) in
//            make.centerY.equalToSuperview()
//            make.left.equalToSuperview().offset(10)
//        }
//        addressBox.drawLabel(label: addressLab, text: "选择收货地址", fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
//            make.centerY.equalToSuperview()
//            make.left.equalToSuperview().offset(41.5)
//            make.right.equalToSuperview().offset(-30)
//        }
//        addressLab.numberOfLines = 0
        addressBox.drawView(view: addressView) { (make) in
            make.left.right.equalToSuperview()
            make.top.bottom.equalToSuperview()
        }
        if addressView.subviews.count > 0 {
            return addressBox
        }
        addressView.drawSubviews()
        addressView.drawImage(named: "youjiantou_55") { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
        }
        addressView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(addressViewTap(tap:))))
        
//        safeView.drawView(view: addressView) { (make) in
//            make.top.equalTo(headView.snp.bottom).offset(10)
//            make.left.right.equalToSuperview()
//        }
//        addressView.backgroundColor = .white
        return addressBox
    }
    
}

// MARK: event & action
extension M_OrderVC {
    
    @objc func _buyButtonClick(button: Button) {
        if iscar {
            orderData.zoneCode = proAry[0].getString("zoneCode") ?? ""
            orderData.remark = footView.remark.text
            
            if let orderDeliverModeCode = curAdDic.getString("orderDeliverModeCode"),let orderDeliverSiteCode = curAdDic.getString("orderDeliverSiteCode") {
                orderData.orderDeliverModeCode = orderDeliverModeCode
                orderData.orderDeliverSiteCode = orderDeliverSiteCode
                submitOrderCar(orderdata: orderData, callback: { (dl) in
                    let vc = M_PayVC(dl,price: self.sumLab.text)
                    self.pushViewController(vc)
                })
            }
            else {
                let popup = PopupBox(infoText: "请填写您的地址")
                popup.show(vc: UIViewController.topMostController() ?? self)
                return
            }
            
        }
        else {
            let zonecode = proAry[0].getString("zoneCode") ?? ""
            var items = [[String:Any?]]()
            for item in proAry {
                var i = [String:Any?]()
                i.updateValue(item.getString("productNo"), forKey: "productNo")
                i.updateValue(1, forKey: "productNum")
                items.append(i)
            }
            if let orderDeliverModeCode = curAdDic.getString("orderDeliverModeCode"),let orderDeliverSiteCode = curAdDic.getString("orderDeliverSiteCode") {

                submitOrderData(orderDeliverModeCode: orderDeliverModeCode, orderDeliverSiteCode: orderDeliverSiteCode,
                                zoneCode: zonecode, remark: footView.remark.text ?? "", items: items, callback: { (dl) in
                                    let vc = M_PayVC(dl,price: self.sumLab.text)
                                    self.pushViewController(vc)
                })
            }
            else {
                let popup = PopupBox(infoText: "请填写您的地址")
                popup.show(vc: UIViewController.topMostController() ?? self)
                return
            }
            
        }
    }
    
    @objc func _kefuButtonClick(button: Button) {
        let vc = M_SimpleArticleVC()
        pushViewController(vc)
        let qidiandic = LocalStorage.getDic(forKey: QIDIAN_KEY)
        vc.loadUrl(qidiandic?.getString("id") ?? "https://url.cn/50hfdES?_type=wpa&qidian=true")

        vc.headTitle.text = "联系客服"
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func addressViewTap(tap:UITapGestureRecognizer){
        let vc = M_AddressListVC()
        var dl : [String:Any?]?
        if proAry.count > 0 {
            dl = proAry[0]
        }
        let zoneCode = dl?.getString("zoneCode") ?? ""
        vc.zoneCode = zoneCode
        pushViewController(vc)
        vc.callSaveBlock { (dic) in
            self.curAdDic = dic
            
            self.addressView.nameAndMobileLabel.text = "\(dic.getString("receiptName") ?? "") \(dic.getString("mobile") ?? "")"
            if self.addressView.nameAndMobileLabel.text?.count ?? 0 > 1 {
                self.addressView.addressLabel.text = dic.getString("name")
                self.addressView.noneLabel.text = ""
            }
            else {
                self.addressView.noneLabel.text = dic.getString("name")
                self.addressView.addressLabel.text = ""
            }
            self.setupFootView()
            self.tableView.reloadData()
        }
        vc.headTitle.text = "配送地址"
    }
    
   ///MARK: UITableViewDelegate
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
    }
    
    ///MARK: UITableViewDataSource
    
    //组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            return proAry.count
        }else{
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            return nil
        }
        let head = UIView()
        head.backgroundColor = .white
        let titlelab = head.drawLabel(text: "京东配送", fontSize: 12, textColor: .x333333) { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(20)
        }
        if proAry[0].getString("zoneCode") == "105002"  {
            titlelab.text = "京东配送"
        }
        else {
            titlelab.text = "自营专区"
        }
        
        head.drawImage(named: "youjiantou_55") { (make) in
            make.left.equalTo(titlelab.snp.right).offset(10)
            make.centerY.equalTo(titlelab)
        }
        return head
    }
    
    //头高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section==0 {
            return 9
        }
       return 45
    }
    
    //尾部高度
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section==0 {
            return 10
        }
        return 240
    }
    
    //尾部view
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section==0 {
            return nil
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.initKeyboardObserver()
            self.fillAccessoryToolBar()
        }
        return footView
    }
    
    // 设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return UITableView.automaticDimension
        }
        return 120
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return UITableView.automaticDimension
        }
        return 120
    }
    
    

    // UITableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell : UITableViewCell
            let cell_ = tableView.dequeueReusableCell(withIdentifier: M_OrderVC.addressIDStr )
            if cell_ == nil {
                cell = UITableViewCell(style: .default, reuseIdentifier: M_OrderVC.addressIDStr)
            }else{
                cell = cell_!
            }
            if cell.contentView.subviews.count == 0 {
                _ = drawAddressBox(parentView:cell.contentView)
            }
            return cell
        }
        
        var cell = tableView.dequeueReusableCell(withIdentifier: M_OrderVC.cellIDStr ) as? M_OrderCell
        if cell==nil {
            cell = M_OrderCell(style: .subtitle, reuseIdentifier: M_OrderVC.cellIDStr)
        }
        
        cell?.celldata = proAry[indexPath.row]
        return cell!
    }
}

class M_OrderAddressView : UIView {
    let nameAndMobileLabel = UILabel()
    let addressLabel = UILabel()
    let noneLabel = UILabel()
    
    func drawSubviews(){
        drawImage(named: "xuanzhedizhi_93") { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
        }
        drawLabel(label: nameAndMobileLabel, text: nil, fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.left.equalToSuperview().offset(41.5)
            make.right.equalToSuperview().offset(-30)
            make.top.equalToSuperview().offset(16.0)
        }
        nameAndMobileLabel.numberOfLines = 1
        
        drawLabel(label: addressLabel, text: nil, fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.left.right.equalTo(nameAndMobileLabel)
            make.top.equalTo(nameAndMobileLabel.snp.bottom).offset(10)
            make.bottom.equalToSuperview().offset(-16)
        }
        addressLabel.numberOfLines = 0
        
        drawLabel(label: noneLabel, text: nil, fontSize: 12, fontWeight: .regular, textColor: .x333333) { (make) in
            make.left.right.equalTo(nameAndMobileLabel)
            make.centerY.equalToSuperview()
        }
        addressLabel.numberOfLines = 0
        addressLabel.lineBreakMode = .byWordWrapping
        addressLabel.horizontalFittingSize()
    }
}
